﻿using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Security.Principal;
using System.ServiceModel;
using System.ServiceModel.Activation;
using Acaweb.Common;
using Acaweb.Model.Entities;
using Acaweb.Servicios.Security;
using Acaweb.Servicios.Utility;
using Components = Acaweb.Componentes.Contracts;

namespace Acaweb.Servicios.Services
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class AuthenticationService : Contracts.IAuthenticationService
    {
        PrincipalContext Context = new PrincipalContext(ContextType.Domain, "192.168.100.110", "DC=USBCTG,DC=LOCAL", "user_moodle", "moodle2008");

        public Utility.ServiceResponse Login(string Username, string Password)
        {
            bool IsValid = Context.ValidateCredentials(Username, Password);

            if (IsValid)
            {
                string Token = Guid.NewGuid().ToString();
                UserPrincipal LoggedUser = UserPrincipal.FindByIdentity(Context, IdentityType.SamAccountName, Username);

                User CurrentUser = new Security.User
                {
                    Name = LoggedUser.GivenName + " " + LoggedUser.Surname,
                    Username = LoggedUser.Name,
                    Email = LoggedUser.EmailAddress,
                    Token = Token,
                    //AlterUsername = Username
                };

                CurrentUser.UpdateRol();

                Components.ISessionsService _SessionComponent = AppCtx.Resolve<Components.ISessionsService>();

                Acaweb.Model.Entities.Sessions Session = new Model.Entities.Sessions
                {
                    SessionId = Token,
                    Created = DateTime.Now,
                    Expires = DateTime.Now.AddMinutes(1000),
                    SessionItems = Username,
                    ApplicationName = "AcaWeb",
                    Locked = 0
                };

                _SessionComponent.Create(Session);

                ServiceResponse SR = new ServiceResponse { Message = "LOGIN_SUCCESSFULL", Success = IsValid, User = CurrentUser };

                return SR;
            }
            else
                //return new User(); ;
                return new ServiceResponse { Message = "USER_OR_PASSWORD_INCORRECT", Success = IsValid };
        }

        public static string GetUserEmail(string Username)
        {
            PrincipalContext Context = new PrincipalContext(ContextType.Domain, "192.168.100.110", "DC=USBCTG,DC=LOCAL", "user_moodle", "moodle2008");
            return UserPrincipal.FindByIdentity(Context, IdentityType.SamAccountName, Username).EmailAddress;
        }

        public Security.User GetCurrentUser()
        {
            return AuthenticationService.GetCurrent(Context);
        }

        public static Security.User GetCurrent()
        {
            PrincipalContext Context = new PrincipalContext(ContextType.Domain, "192.168.100.110", "DC=USBCTG,DC=LOCAL", "user_moodle", "moodle2008");

            IIdentity Current = ServiceSecurityContext.Current.PrimaryIdentity;

            if (!String.IsNullOrEmpty(Current.Name))
            {
                UserPrincipal LoggedUser = UserPrincipal.FindByIdentity(Context, Current.Name.Replace(" ",""));

                User User = new Security.User { Name = LoggedUser.GivenName + " " + LoggedUser.Surname, Username = Current.Name, Email = LoggedUser.EmailAddress };

                User.UpdateRol();

                return User;
            }
            return null;
        }

        public static Security.User GetCurrent(PrincipalContext Context)
        {
            IIdentity Current = ServiceSecurityContext.Current.PrimaryIdentity;

            if (!String.IsNullOrEmpty(Current.Name))
            {
                UserPrincipal LoggedUser = UserPrincipal.FindByIdentity(Context, IdentityType.SamAccountName, Current.Name);

                User User = new Security.User { Name = LoggedUser.DisplayName, Username = Current.Name, Email = LoggedUser.EmailAddress };

                User.UpdateRol();

                return User;
            }
            return null;
        }

        public List<Estudiantes> GetByDocumentoIdentidad(int DocumentoIdentidad)
        {
            Components.IEstudiantesService _EstudianteComponent = AppCtx.Resolve<Components.IEstudiantesService>();
            return _EstudianteComponent.GetDocumentosIdentificacion(DocumentoIdentidad).ToList();
        }
    }
}